import {
  FFmpegKit,
  FFmpegKitConfig,
  ReturnCode,
} from "ffmpeg-kit-react-native";
import * as FileSystem from "expo-file-system";
import * as MediaLibrary from "expo-media-library";
import { Alert } from "react-native";
import { getCommand, getOutputPath } from "./ffmpeg";

interface VideoTask {
  id: string;
  inputPath: string;
  outputPath: string;
  progress: number;
  status: "pending" | "processing" | "paused" | "completed" | "failed";
  task?: any;
  operation: string;
  index: number;
  sessionId: number;
}

// const saveToGallery = async (filePath) => {
//   const { status } = await MediaLibrary.requestPermissionsAsync();
//   if (status !== "granted") {
//     Alert.alert("相册权限被拒绝，保存失败");
//   }

//   await MediaLibrary.createAssetAsync(filePath);
// };

class ProcessingQueue {
  queue: VideoTask[];
  current: any;
  isPaused: boolean;
  onProgress: (index: number) => void;
  onPausecb: (isPaused: boolean) => void;
  constructor() {
    this.queue = [];
    this.current = null;
    this.isPaused = false;
    this.onProgress = () => {};
    this.onPausecb = () => {};
  }

  saveToGallery = async (filePath) => {
    const { status } = await MediaLibrary.requestPermissionsAsync();
    if (status !== "granted") {
      // Alert.alert("相册权限被拒绝，保存失败");
    }
    try {
      await MediaLibrary.createAssetAsync(filePath);
      await FileSystem.deleteAsync(filePath);
    } catch (error) {
      Alert.alert("Error", JSON.stringify(error));
    }
  };

  addTask(task) {
    this.queue.push(task);
    if (!this.current) this.processNext();
  }

  // 更新任务状态
  updateTaskStatus = (index: number, status: VideoTask["status"]) => {
    const newTasks = [...this.queue];
    newTasks[index].status = status;
    return newTasks;
  };

  async processNext() {
    if (this.isPaused || this.queue.length === 0) {
      this.current = null;
      return;
    }

    try {
      const nextIndex = this.queue.findIndex(
        (task) => task.status === "pending" || task.status === "paused"
      );

      if (nextIndex === -1) return;
      const taskToProcess = this.queue[nextIndex];
      this.current = taskToProcess;
      const { inputPath, outputPath, operation } = taskToProcess;

      // 更新任务状态为处理中
      this.updateTaskStatus(nextIndex, "processing");
      const command = await getCommand(inputPath, outputPath, operation);
      FFmpegKit.executeAsync(command).then((session) => {
        const sessionId = session.getSessionId();
        const updatedTasks = [...this.queue];
        updatedTasks[nextIndex].sessionId = sessionId;
        this.queue = updatedTasks;
      });

      FFmpegKitConfig.enableFFmpegSessionCompleteCallback(async (session) => {
        const returnCode = await session.getReturnCode();
        if (ReturnCode.isSuccess(returnCode)) {
          // 检查文件是否存在
          const fileInfo = await FileSystem.getInfoAsync(outputPath);
          if (!fileInfo.exists) {
            // Alert.alert("降低重复度文件为空", JSON.stringify(returnCode));
          }

          // 保存到相册（需要权限）
          await this.saveToGallery(outputPath);
          this.onProgress(nextIndex);
          this.updateTaskStatus(nextIndex, "completed");
          this.processNext();
        } else if (ReturnCode.isCancel(returnCode)) {
          // Alert.alert("ss", "CANCEL");
          // CANCEL
        } else {
          Alert.alert('处理失败,请退出重试')
          this.updateTaskStatus(nextIndex, "failed");
          // Alert.alert("降低重复度", JSON.stringify(returnCode));
        }
      });
    } catch (err) {
      Alert.alert("Task failed:", `${err}`);
      console.error("Task failed:", err);
    } finally {
    }
  }

  pause() {
    this.isPaused = true;
    this.onPausecb(true);
    if (this.current) {
      FFmpegKit.cancel(this.current?.sessionId).then(() => {
        const outputPath = getOutputPath(
          this.current?.inputPath,
          this.current?.operation
        );
        const index = this.current?.index;
        const updatedTasks = [...this.queue];
        const newTask = {
          id: `task-${Date.now()}-${index}`,
          inputPath: this.current?.inputPath,
          outputPath,
          operation: this.current?.operation,
          status: "completed" as const,
          index,
        };
        updatedTasks[index] = newTask;
        this.queue = updatedTasks;
        this.current = newTask;
      });
    }
  }

  resume() {
    this.isPaused = false;
    this.onPausecb(false);
    if (this.current?.index === this.queue?.length - 1) {
      this.onProgress(this.current?.index);
    }
    this.processNext();
  }

  cancelAll() {
    this.queue = [];
    this.current = null;
    FFmpegKit.cancel();
  }

  reset() {
    this.queue = [];
    this.current = null;
  }
}

export default ProcessingQueue;
